# coding=utf-8
from flask import Flask, request, jsonify, render_template
import pymysql
pymysql.install_as_MySQLdb()
from flask_sqlalchemy import SQLAlchemy
import json


app = Flask(__name__)

#设置连接数据库的URL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456yjk@localhost:3306/wokerManager'


db = SQLAlchemy(app)

class Role(db.Model):
    # 定义表名
    __tablename__ = 'roles'
    # 定义列对象
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    use = db.relationship('User', backref='role')

    #repr()方法显示一个可读字符串
    def __repr__(self):
        return 'Role:%s'% self.name

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64),unique=True, nullable=False)
    phone = db.Column(db.String(11), nullable=False)
    pswd = db.Column(db.String(64))
    age = db.Column(db.Integer, nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    def to_dict(self):
        lis_dic = {
            "user_id": self.id,
            "username": self.username,
            "email": self.email,
            "age": self.age,
            "mobile": self.phone
        }
        return lis_dic


    def __repr__(self):
        return 'User:%s'%self.username

@app.route('/worker/login', methods=["GET"])
def login():
    return render_template('index.html')


# 此接口采用restful风格
@app.route('/worker/user/<id>', methods=["GET", "POST", "DELETE","PUT"])
def user(id):
    # get请求下有两种情况
    if request.method == 'GET':
        # 如果id为all意味中是前端要获取所有员工的信息除了管理员
        if id == 'all':
            users = User.query.filter(User.role_id==2).all()
            all_user_list = []
            for user in users:
                all_user_list.append(user.to_dict())
            return jsonify(msg=200, data=all_user_list)
        else:
            # 如果不为all就意味着查询单个woker 的详情，或者id值不规范
            user = User.query.get(id)
            print(user)
            # 如果没有找到相应woeker 的信息返回none
            if not user:
                return jsonify(msg=200, data=None)
            else:
                return jsonify(msg=200, data=user.to_dict())

    # 修改worker
    if request.method == 'PUT':
        
        res = request.get_json()
        username = res.get('username')
        email = res.get('email')
        phone = res.get('phone')
        age = res.get('age')
        if not all((phone, email, username, age)):
            return jsonify(errno=1, errmsg='参数不完整')
        User.query.filter_by(id=id).update({'username':username, 'email': email, 'phone': phone, 'age':age})
        # user = User(name=username, phone=phone,  email=email, age=age, role_id=2)
        # db.session.add(user)
        db.session.commit()
        return jsonify(msg=200, data='修改成功')

    # 如果是post请求则是增加woker
    if request.method == 'POST':
        pass

    # 删除worker
    if request.method == "DELETE":
        pass
        



if __name__ == "__main__":
    #  这是鉴婊的时候才执行，一次就可以了
    # db.drop_all()
    # db.create_all()
    # ro1 = Role(name='admin')
    # ro2 = Role(name='user')
    # db.session.add_all([ro1,ro2])
    # db.session.commit()
    # us1 = User(name='wang',email='wang@163.com', age=1, pswd='123456', phone='12345678901',role_id=ro1.id)
    # us2 = User(name='zhang',email='zhang@189.com', age=2,  phone='12345678901', role_id=ro2.id)
    # us3 = User(name='chen',email='chen@126.com', age=3,  phone='12345678901',role_id=ro2.id)
    # i = 100
    # while i>0:
    #     username = 'yang%s' % i 
    #     email = 'zhou@163%s.com' %i
    #     us4 = User(username=username,email=email, age=4, phone='12345678901',role_id=2)

    #     db.session.add(us4)
    #     db.session.commit()
    #     i = i-1


    app.run(debug=True, host='0.0.0.0')